<template>
  <div class="followAdd" v-loading="detailInfoShow">
    <!-- 筛选按钮 -->
    <div
      class="search-button"
      v-if="pageType !== 'detail' && pageType !== 'check'"
    >
      <!-- <el-button
        v-if="pageType !== 'detail' && pageType !== 'check'"
        class="btn save"
        @click="handleAddSave(followFormRef)"
        ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
        >保存</el-button
      > -->
      <el-button class="btn back" @click="handleBack"
        ><el-icon class="icon" color="#fff"> <Back /> </el-icon
        >返回</el-button
      >
    </div>
    <el-collapse v-model="activeNames">
      <!-- 基础信息 -->
      <el-collapse-item
        name="1"
        v-if="pageType !== 'detail' && pageType !== 'check'"
        class="transform-down"
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">任务信息</span>
        </template>
        <div class="follow-info">
          <el-form
            :model="followForm"
            ref="followFormRef"
            :rules="queryRules"
            label-width="120px"
            v-enterToNext
            :disabled="pageType === 'detail'"
          >
            <el-row>
              <el-col :span="6">
                <el-form-item label="任务名称：">
                  <el-input
                    style="width: 100%"
                    v-model="followForm.maintanceTaskName"
                    placeholder=""
                    clearable
                    class="search-input"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="分配时间：">
                  <el-input
                    style="width: 100%"
                    v-model="followForm.createTime"
                    placeholder=""
                    clearable
                    class="search-input"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="计划开始时间：">
                  <el-input
                    style="width: 100%"
                    v-model="followForm.startTime"
                    placeholder=""
                    clearable
                    class="search-input"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="距离开始天数：">
                  <el-input
                    style="width: 100%"
                    v-model="followForm.startTimeNum"
                    placeholder=""
                    clearable
                    class="search-input"
                    disabled
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="计划结束时间：">
                  <el-input
                    style="width: 100%"
                    v-model="followForm.endTime"
                    placeholder=""
                    clearable
                    class="search-input"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="距离结束天数：">
                  <el-input
                    style="width: 100%"
                    v-model="followForm.endTime"
                    placeholder=""
                    clearable
                    class="search-input"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="备注：">
                  <el-input
                    maxlength="2000"
                    style="width: 100%"
                    v-model="followForm.remark"
                    placeholder=""
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="6" v-if="followForm.workOrderType === 4">
                <el-form-item label="故障类型：" prop="faultType">
                  <el-select
                    v-model="followForm.faultType"
                    placeholder="请选择"
                    clearable
                    class="search-input"
                  >
                    <el-option
                      v-for="dict in typeList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="申请物料：" prop="">
                  <div class="material-box" v-if="materialList.length">
                    <span v-for="(item, index) in materialList" :key="item"
                      ><span
                        @click="handleToMaterial(item)"
                        class="material-text"
                        >{{ item.deliveryApplyCode }}</span
                      ><span v-if="index + 1 != materialList.length"
                        >，</span
                      ></span
                    >
                  </div>
                  <div class="material-text" v-else>暂无物料</div>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="反馈情况：" prop="feedback">
                  <el-select
                    :disabled="!['进行中'].includes(constructionStatusName)"
                    v-model="followForm.feedback"
                    placeholder="请选择"
                    clearable
                    class="search-input"
                  >
                    <el-option
                      v-for="dict in caseList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="防区：">
                  <el-input
                    v-model="followForm.armedzoneName"
                    placeholder="自动获取"
                    clearable
                    class="search-input"
                    disabled
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="防区点位：">
                    <el-input
                      v-model="followForm.pointList"
                      placeholder="自动获取"
                      clearable
                      class="search-input"
                      disabled
                    >
                    </el-input>
                    <!-- followForm.projectTaskDetailInfoRespVos -->
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="防区设备：">
                  <div v-if="deviceList.length > 0" class="tag tag-box">
                    <el-tag
                      v-for="(tag, index) in deviceList"
                      :key="index"
                      :disable-transitions="false"
                      style="margin-right: 4px"
                    >
                      {{ tag.armedzoneName.split(":")[0] }}
                    </el-tag>
                  </div>
                  <div v-else class="tag tag-box">
                    <i
                      style="color: gray; font-style: inherit; font-size: 14px"
                    >
                      暂无设备
                    </i>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="工单关结描述：" prop="workDesc">
                  <el-input
                    :disabled="!['进行中'].includes(constructionStatusName)"
                    style="width: 100%"
                    v-model="followForm.workDesc"
                    type="textarea"
                    maxlength="2000"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="交付文件：">
                  <Upload
                    :disabled="!['进行中'].includes(constructionStatusName)"
                    :fileList="followForm.suppFileInfoVos"
                    :limit="10"
                    limitation="templatelimitation"
                    accept=".doc,.docx"
                    :isFull="true"
                    :isCanDelete="true"
                    :showButton="true"
                    @success="(result) => uploadSuccess(result)"
                    @deleteFile="(result) => uploadRemove(result)"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div class="footer-button">
            <!-- v-if="form.implStatus === 0" -->
            <!-- v-if="" -->
            <el-button
              v-if="['已分配'].includes(constructionStatusName)"
              v-preventReClick
              size="mini"
              type="primary"
              @click="handleTaskOperate(1, followFormRef)"
            >
              退回当前任务
            </el-button>
            <!-- v-if="form.implStatus === 0" -->
            <el-button
              v-if="['已分配'].includes(constructionStatusName)"
              v-preventReClick
              size="mini"
              type="primary"
              @click="handleTaskOperate(2, followFormRef)"
            >
              开始当前任务
            </el-button>
            <!-- v-if="form.implStatus === 1" -->
            <el-button
              v-if="['进行中'].includes(constructionStatusName)"
              v-preventReClick
              size="mini"
              type="primary"
              @click="handleTaskOperate(3, followFormRef)"
            >
              提交当前任务
            </el-button>
          </div>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script setup>
import Upload from "@/components/Upload/index";
import {
  getEndFollowApi,
  addFollowApi,
  getProjectApi,
} from "@/api/sales/project";
import {
  getWorkTaskDetailApi,
  getWorkMaterialDetailApi,
  workReturnTaskApi,
  workSubmitTaskApi,
} from "@/api/operation/work";
import {
  getArmedzoneDeviceApi,
} from "@/api/operation/flightdata.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { getDictsApi } from "@/api/dict";
const emit = defineEmits([
  // 刷新父组件表格数据
  "refreshList",
  // 更新跟进组件显隐
  "update:followAddShow",
]);
const props = defineProps({
  // 操作类型
  pageType: {
    type: String,
    default: "add",
  },
});
// 路由
const router = useRouter();
// 折叠栏默认展开
const activeNames = ref(["1", "2", "3"]);
// 客户表单引用
const followFormRef = ref();
// 详情加载效果
const detailInfoShow = ref(false);
// 输入框引用
const refInput = ref();
// 故障类型列表
const typeList = ref([]);
// 反馈情况列表
const caseList = ref([]);
// 申请物料列表
const materialList = ref([]);
const constructionStatusName = ref("");
// 设备列表
const deviceList = ref([]);
// 跟进表单引用
const followFormTemplate = {
  maintanceTaskName: "", // 任务名称
  createTime: "", // 分配时间
  startTime: "",
  endTime: "",
  startTimeNum: "",
  endTimeNum: "",
  remark: "",
  // 工单类型
  workOrderType: null,
  // ————————————————————————————
  faultType: null, // 故障类型
  feedback: null, // 反馈情况
  maintanceTaskId: null, // 工单任务
  workDesc: "", // 	工单关结描述
  suppFileInfoVos: [], // 交付物-类型传16
  type: 0, // 按钮类型0：开始；1；提交
  workOrderId: null, // 工单id
  applyMaterial: "",
};
const data = reactive({
  // 跟进表单
  followForm: JSON.parse(JSON.stringify(followFormTemplate)),
  // 跟进表单校验规则
  queryRules: {
    workDesc: [
      { required: true, message: "请输入工单关结描述", trigger: "blur" },
    ],
    suppFileInfoVos: [
      { required: true, message: "请选择交付物", trigger: "change" },
    ],
    feedback: [
      { required: true, message: "请选择反馈情况", trigger: "change" },
    ],
    faultType: [
      { required: true, message: "请选择故障类型", trigger: "change" },
    ],
  },
});
const { followForm, queryRules } = toRefs(data);

/**
 * @description: 保存
 * @param {Object} followFormRef 跟进表单引用
 */
const handleAddSave = async (followFormRef) => {
  if (!followFormRef) return;
  await followFormRef.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          const res = await addFollowApi(followForm.value);
          if (res.code === 200) {
            emit("update:followAddShow", false);
            emit("refreshList", false);
            ElMessage.success(res.msg);
            followForm.value = JSON.parse(JSON.stringify(followFormTemplate));
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
    }
  });
};

/**
 * @description: 返回
 */
const handleBack = () => {
  ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "confirmBtnClass",
    cancelButtonClass: "cancelBtnClass",
  })
    .then(async () => {
      emit("update:followAddShow", false);
      followForm.value = JSON.parse(JSON.stringify(followFormTemplate));
    })
    .catch(() => {});
};

/**
 * @description: 文件上传成功处理
 * @param {Object} response 文件信息
 */
function uploadSuccess(response) {
  followForm.value.suppFileInfoVos.push({ ...response, businessType: 16 });
}

/**
 * @description: 删除文件
 * @param {Number} index 当前文件索引
 */
function uploadRemove(index) {
  followForm.value.suppFileInfoVos.splice(index, 1);
}

/**
 * @description: 处理详情信息
 * @param {Number} id
 */
const handleDetailInfo = async (row) => {
  const id = row.workOrderId;
  followForm.value.workOrderId = id;
  followForm.value.workOrderType = row.workOrderType;
  constructionStatusName.value = row.constructionStatusName;
  try {
    const res = await getWorkTaskDetailApi(id);

    if (res) {
      followForm.value = { ...followForm.value, ...res };
      getArmedzoneDevice()
      if (!followForm.value.suppFileInfoVos) {
        followForm.value.suppFileInfoVos = [];
      }
      if(followForm.value.projectTaskDetailInfoRespVos) {
        let resultArray = followForm.value.projectTaskDetailInfoRespVos.map(
          (item) => item.pointAdd
        );
        let resultString = resultArray.join(",");
        followForm.value.pointList = resultString
      }
    }

    const resMaterial = await getWorkMaterialDetailApi(id);
    console.log('resMaterial')
    console.log(resMaterial)
    materialList.value = resMaterial || [];
    // resMaterial.forEach((item, index) => {
    //   followForm.value.applyMaterial =
    //     followForm.value.applyMaterial + item.deliveryApplyCode;
    //   if (index + 1 !== resMaterial.length) {
    //     followForm.value.applyMaterial = followForm.value.applyMaterial + ",";
    //   }
    // });
  } catch (error) {}
};

// 设备列表
const getArmedzoneDevice = () => {
  if (followForm.value.armedzoneId) {
    getArmedzoneDeviceApi(followForm.value.armedzoneId).then((res) => {
      deviceList.value = res;
    });
  } else {
    deviceList.value = [];
  }
};

/**
 * @description: 跳转物料详情
 * @param {Number} id
 */
const handleToMaterial = (item) => {
  const { href } = router.resolve({
    path: `/stock/outorder`,
    query: { deliveryApplyId: item.deliveryApplyId },
  });
  window.open(href, "_blank");
};

/**
 * @description: 处理任务操作
 * @param {Number} type 1.退回 2.开始 3.提交
 */
const handleTaskOperate = async (type, followFormRef) => {
  switch (type) {
    // 退回
    case 1:
      ElMessageBox.prompt("退回原因：", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPlaceholder: "请输入",
        inputPattern: /\S/,
        inputErrorMessage: "请输入退回原因",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async ({ value }) => {
          constructionStatusName.value = "已退回";
          const arr = {
            maintanceTaskId: followForm.value.maintanceTaskId, // 任务id
            returnReasons: value, // 退回原因
            workOrderId: followForm.value.workOrderId, // 工单id
          };
          const res = await workReturnTaskApi(arr);
          if (res.code === 200) {
            emit("update:followAddShow", false);
            emit("refreshList", false);
            ElMessage.success(res.msg);
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;
    // 开始
    case 2:
      ElMessageBox.confirm("此操作将开始当前任务，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
        type: "warning",
      })
        .then(async () => {
          constructionStatusName.value = "进行中";
          followForm.value.type = 0;
          const res = await workSubmitTaskApi(followForm.value);
          if (res.code === 200) {
            emit("update:followAddShow", false);
            emit("refreshList", false);
            ElMessage.success(res.msg);
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});

      break;
    // 提交
    case 3:
      await followFormRef.validate(async (valid, fields) => {
        if (valid) {
          ElMessageBox.confirm("此操作将完成当前任务，是否继续？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            confirmButtonClass: "confirmBtnClass",
            cancelButtonClass: "cancelBtnClass",
            type: "warning",
          })
            .then(async () => {
              constructionStatusName.value = "已完成";
              followForm.value.type = 1;
              const res = await workSubmitTaskApi(followForm.value);
              if (res.code === 200) {
                emit("update:followAddShow", false);
                emit("refreshList", false);
                ElMessage.success(res.msg);
              } else {
                ElMessage.error(res.msg);
              }
            })
            .catch(() => {});
        }
      });
      break;
    default:
      break;
  }
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  await getDictsApi("erp_feedback").then((res) => {
    // 反馈情况列表
    if (res.code === 200) {
      caseList.value = res.data;
    }
  });

  await getDictsApi("erp_fault_type").then((res) => {
    // 故障类型列表
    if (res.code === 200) {
      typeList.value = res.data;
    }
  });
}

onMounted(() => {
  getDicts();
  if (props.pageType !== "detail" && props.pageType !== "check") {
    nextTick(() => {
      setTimeout(() => {
        refInput.value.focus();
      }, 800);
    });
  }
});

defineExpose({
  handleDetailInfo,
});
</script>
<style lang="scss" scoped>
.followAdd {
  padding: 20px;
  width: 100%;
  height: 100%;
  .follow-info {
    padding: 20px 10px 5px 10px;
    background-color: #f0f0f0;
    margin: 10px 0;
  }
  .follow-detail-info {
    margin-top: 20px;
  }
  .footer-button {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    padding-bottom: 20px;
  }
  :deep(.el-form-item--default) {
    margin-bottom: 22px;
  }
  :deep(.el-form-item--default .el-form-item__error) {
    padding-top: 5px;
  }
  .material-box {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    .material-text {
      cursor: pointer;
      &:hover {
        color: #409eff;
      }
    }
  }
}
</style>
